package com.lbn.baseframe.net;

import android.content.Context;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author 李炳南
 * @date 2017/2/8
 */
public class Retrofit2Config {

    private static Retrofit2Config mRtf2Config;

    private static HashMap<String, Retrofit> rtfMap;

    private Retrofit2Config() {
    }

    public static Retrofit2Config getInstance() {

        if (mRtf2Config == null) {
            synchronized (Retrofit2Config.class) {
                if (mRtf2Config == null) {
                    mRtf2Config = new Retrofit2Config();
                    rtfMap = new HashMap<>();
                }
            }
        }
        return mRtf2Config;
    }


    private  OkHttpClient provideOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS);
        builder.readTimeout(30 * 1000, TimeUnit.MILLISECONDS);
        builder.addInterceptor(new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
            .setLevel(HttpLoggingInterceptor.Level.BODY));
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder.build();
    }


    private  Retrofit provideRetrofit(OkHttpClient okHttpClient, String host) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(host)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit;
    }


    public  <T> T getRetrofit(IRetrofit2Host host, Class<T> clazz) {
        String h = host.getHost();
        Retrofit retrofit = rtfMap.get(h);
        if (retrofit == null) {
            retrofit = provideRetrofit(provideOkHttpClient(),h);
            rtfMap.put(h, retrofit);
        }
        return retrofit.create(clazz);
    }


}
